<template>
  <div id="ccMap-div">
    <div id="pickerInput">
      <el-input v-model="pickerInput" id="ccMap-pickerInput" placeholder="输入你需要搜索的地点" />
      <div id="ccMap-suggestContainer"></div>
    </div>
    <div id="ccMap-container"></div>
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader';
export default {
  name: 'ccMap',
  components:{
  },
  props:{
    lng:{
      type: Number,
      default: 116.397428,
    },
    lat:{
      type: Number,
      default: 39.90923
    },
    keywords:{
      type:String,
      default:''
    }
  },
  watch:{
    keywords(newVal,oldVal){
      console.log("newVal",newVal);
      console.log("oldVal",oldVal);
      if(newVal === undefined || newVal === ''){
        this.pickerInput = newVal;
      }else{
        this.pickerInput = oldVal;
      }
    },
    position:{
      handler(newVal,oldVal){
        if (newVal !== oldVal){
          //查询当前的城市
          this.searchCityByLng(newVal.lat,newVal.lng,(cityId)=>{
            if(!this.initFlag){
              this.$emit("getPosition",newVal)
            }
            this.initFlag = false;
            this.$set(newVal,"cityId",cityId)
          })
        }
      },
      immediate:true
    },
    lng:{
      handler(newVal,oldVal){
        if (newVal !== oldVal) this.updatePositionAndMarker()
      },
    },
    lat:{
      handler(newVal,oldVal){
        if (newVal !== oldVal) this.updatePositionAndMarker()
      },
    },
  },
  data(){
    return{
      pickerInput:undefined,
      map:undefined,
      marker:undefined,
      position:undefined,
      initFlag:false,
    }
  },
  created() {
    this.initFlag = true;
    this.initCcMap()
  },
  methods:{
    initCcMap(){
      AMapLoader.load({
        "key": "c398a59c7024547ef16dfad5cf4d3f35",              // 申请好的Web端开发者Key，首次调用 load 时必填
        "version": "2.0",   // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        "plugins": ['AMap.PlaceSearch'],           // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        "AMapUI": {             // 是否加载 AMapUI，缺省不加载
          "version": '1.1',   // AMapUI 缺省 1.1
          "plugins":['misc/PoiPicker'],       // 需要加载的 AMapUI ui插件
        },
        "Loca":{                // 是否加载 Loca， 缺省不加载
          "version": '2.0'  // Loca 版本，缺省 1.3.2
        },
      }).then((AMap)=>{
        let _this = this
        // 创建一个 Marker 实例：
        _this.marker = new AMap.Marker({
          position: new AMap.LngLat(_this.lng, _this.lat),   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
          title: '选中位置',
          clickable: false,
          draggable: true
        });
        //监听marker移动事件
        _this.marker.on('dragend',function(result){
          _this.position = result.lnglat
        })

        //设置DomLibrary，jQuery或者Zepto
        AMapUI.setDomLibrary($);

        AMapUI.loadUI(['misc/PoiPicker'], function(PoiPicker) {
          //实例化地图
          _this.map = new AMap.Map('ccMap-container', {
            zoom: (_this.lng === 116.397428 && _this.lat === 39.90923)?2:16,//级别
            center: [_this.lng, _this.lat],//中心点坐标
            viewMode: '2D'//使用3D视图
          })
          //添加点标记
          _this.map.add(_this.marker)
          //监听地图鼠标左键点击事件
          _this.map.on('click',function(result){
            _this.marker.setPosition(result.lnglat)
            _this.position = result.lnglat
          })
          _this.position = _this.marker.getPosition()
          //插件：poi搜索
          var poiPicker = new PoiPicker({
            input: 'ccMap-pickerInput', //输入框id
            suggestContainer: 'ccMap-suggestContainer'
          });
          console.log("执行");
          console.log("poiPicker",poiPicker);
          //监听poi选中信息
          poiPicker.on('poiPicked', function(poiResult) {
            console.log("poiResult",poiResult);
            //用户选中的poi点信息
            _this.pickerInput = poiResult.item.name
            if (poiResult.item.location){
              _this.map.setZoomAndCenter(16,poiResult.item.location)
              _this.marker.setPosition(poiResult.item.location)
              _this.position = poiResult.item.location
              poiPicker.clearSuggest()
            }else{
              _this.msgError("选中的目标没有一个具体的位置信息")
            }
          });
        });
      }).catch(e => {
        console.log(e);
      })
    },
    updatePositionAndMarker(){
      this.map.setCenter([this.lng,this.lat])
      this.marker.setPosition([this.lng,this.lat])
    },
    searchCityByLng(lat,lng,call){
      var arr = [lng,lat];
      AMap.plugin('AMap.Geocoder', function() {
        var geocoder = new AMap.Geocoder({})
        geocoder.getAddress(arr, (status, result)=> {
          if (status === 'complete' && result.info === 'OK') {
            call(result.regeocode.addressComponent.adcode.substring(0,4) + "00");
          }
        })
      })
    },
  }
}
</script>

<style scoped>
#ccMap-container{
  width: 100%; height: 100%;
  min-width: 50px; min-height: 50px;
}
#ccMap-div{
  width: 100%; height: 100%;
  min-width: 50px; min-height: 50px;
}
#pickerInput{
  position: absolute;
  width: 90%;
  z-index: 999;
  margin: 5px 5% 0;
}
#ccMap-suggestContainer{
  z-index: 999;
  width: 99%;
  margin: auto;
  max-height: 200px;
  overflow: scroll;
  background-color: #ffffff;
  overflow-x: visible;
}
</style>
